//
//  KCTMTKSearchVC.swift
//  BLEManagerSwiftDemo
//
//  Created by Qinsz on 2019/5/22.
//  Copyright © 2019年 Qinsz. All rights reserved.
//


import UIKit
import KCTBluetoothSDK

class KCTMTKSearchVC: UIViewController, UITableViewDelegate, UITableViewDataSource, KCTMTKShellManagerDelegate, KCTSingleBLEShellSearchDelegate {
    
    //MARK: - Property -
    var peripherals = Array<CBPeripheral>.init()
    private let mtkShellManager = KCTMTKShellManager.share
    private let bleShell = KCTSingleBLEShell.sharedInstance // 主要用于搜索时设置MTK设备类型
    
    @IBOutlet weak var tableView: UITableView!
    
    
    //MARK: - View Life Cycle -
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        mtkShellManager.delegate = self
        bleShell.searchDelegate = self
    }
    
    
    //MARK: - Clicks -
    @IBAction func clickSearch(_ sender: Any) {
        peripherals.removeAll()
        tableView.reloadData()
        bleShell.startScan(withServicesFilter: true)
//        if mtkShellManager.shakedHands == false {
            // 容错处理: 已经握手时，调用mtk的搜索方法会导致无法发送消息，且无法重新握手（只有在设置中忽略设备后才能恢复正常）
            DispatchQueue.main.asyncAfter(deadline: .now() + 5,
                                          execute: { [weak self] () in
                self?.mtkShellManager.startScan()
            })
//        }
    }
    
    @IBAction func clickJumpToMTKTasks(_ sender: Any) {
        let mtkVC = KCTMTKTaskSendVC.init(nibName: "KCTMTKTaskSendVC", bundle: Bundle.main)
        self.navigationController?.pushViewController(mtkVC, animated: true)
    }
    
    @IBAction func clickCancelConnect(_ sender: Any) {
        mtkShellManager.cancelConnection()
    }
    
    
    //MARK: - TableView -
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return peripherals.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        var deviceCell : KCTDeviceCell
        if let cell = tableView.dequeueReusableCell(withIdentifier: "KCTDeviceCell") {
            deviceCell = cell as! KCTDeviceCell
        } else {
            deviceCell = Bundle.main.loadNibNamed("KCTDeviceCell", owner: self, options: nil)?.first! as! KCTDeviceCell
        }
        deviceCell.per = peripherals[indexPath.row]
        return deviceCell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        bleShell.stopScan()
        mtkShellManager.startScan()
        let peripheral = peripherals[indexPath.row]
        IPrint("⚠️ KCT MTK \(NSLocalizedString("发起连接", comment: "")) \(peripheral.description) Mac:\(peripheral.macString ?? "--") type:\(peripheral.type.rawValue)")
        if  peripheral.type != .Wear {
            SVProgressHUD.showInfo(withStatus: NSLocalizedString("不是MTK设备", comment: ""))
            return
        }
        
        IPrint("✅ KCT MTK \(NSLocalizedString("发起连接", comment: "")) \(peripheral.description) Mac:\(peripheral.macString ?? "--") type:\(peripheral.type.rawValue)")
        SVProgressHUD.show(withStatus: NSLocalizedString("正在连接...", comment: ""))
        
//        if mtkShellManager.currentPeripheral?.state == .connecting ||
//           mtkShellManager.currentPeripheral?.state == .connected  {
           mtkShellManager.cancelConnection()
//        }
        
        DispatchQueue.main.asyncAfter(deadline: .now() + 3, execute: {
            self.mtkShellManager.connect(peripheral: peripheral, timeout: 15.0)
        })
    }
    
    
    //MARK: - Delagate 回调 -
    // MTK
    func mtkShellManagerShakedHands(manager: KCTMTKShellManager) {
        IPrint("✅ KCT MTK \(NSLocalizedString("连接成功", comment: "")) 🤝")
        SVProgressHUD.showSuccess(withStatus: NSLocalizedString("连接成功", comment: ""))
        mtkShellManager.delegate = nil
        let mtkVC = KCTMTKTaskSendVC.init(nibName: "KCTMTKTaskSendVC", bundle: Bundle.main)
        self.navigationController?.pushViewController(mtkVC, animated: true)
    }
    
    func mtkShellManagerFailedToConnect(manager: KCTMTKShellManager, error: KCTError) {
        SVProgressHUD.showError(withStatus: "❌ KCT MTK \(NSLocalizedString("连接错误", comment: "")) error:  \(error.errInfo)")
        IPrint("❌ KCT MTK \(NSLocalizedString("连接错误", comment: "")) error:  \(error.errInfo)")
    }
    
    func mtkShellManager(manager: KCTMTKShellManager, received cmd: String, activeMessage: Any?) {
        IPrint("\(NSLocalizedString("接收到设备发送的数据", comment: "")):\n cmd:\(cmd)\n message: \n\(activeMessage.debugDescription )")
    }
    
    // MTK 无用，用下方BLE的回调
    func mtkShellManager(scanPeripheral: CBPeripheral) {
        IPrint("⚠️ KCT MTK \(NSLocalizedString("扫描设备", comment: "")) \(scanPeripheral.description) Mac: \(scanPeripheral.macString ?? "--") type: \(scanPeripheral.type.rawValue)")
        for peripheral in peripherals {
            if peripheral.identifier.uuidString == scanPeripheral.identifier.uuidString {
                IPrint("‼️‼️‼️ KCT BLE \(NSLocalizedString("扫描设备", comment: "")) \(peripheral.description)     Mac: \(peripheral.macString ?? "--")     type: \(peripheral.type.rawValue)")
                IPrint("‼️‼️‼️ KCT MTK \(NSLocalizedString("扫描设备", comment: "")) \(scanPeripheral.description) Mac: \(scanPeripheral.macString ?? "--") type: \(scanPeripheral.type.rawValue)")
                scanPeripheral.type = peripheral.type
                peripherals.append(scanPeripheral)
                peripherals.remove(at: peripherals.index(of: peripheral)!)
            }
        }
        tableView.reloadData()
       
    }
    
    // BLE
    func singleBLEShell(shell:KCTSingleBLEShell, didDiscover peripheral:CBPeripheral) {
        IPrint("⚠️ KCT BLE \(NSLocalizedString("扫描设备", comment: "")) \(peripheral.description) Mac: \(peripheral.macString ?? "--") type: \(peripheral.type.rawValue)")
        if  peripherals.contains(peripheral) == false {
            peripherals.append(peripheral)
            tableView.reloadData()
        }
    }
}
